package cn.sanli.manage.service.impl;

import cn.sanli.manage.mapper.data1.UserInfoMapper;
import cn.sanli.manage.mapper.data1.UserOrganizationMapper;
import cn.sanli.manage.mapper.data1.UserRoleMapper;
import cn.sanli.manage.pojo.dto.User.DeleteUserOrganizationDTO;
import cn.sanli.manage.pojo.dto.User.UserOrganizationListDTO;
import cn.sanli.manage.pojo.dto.User.UserOrganizationDTO;
import cn.sanli.manage.pojo.entity.UserInfo;
import cn.sanli.manage.pojo.entity.UserOrganization;
import cn.sanli.manage.pojo.vo.UserOrganizationVO;
import cn.sanli.manage.service.UserOrganizationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用户组织关联表(userOrganization)表服务实现类
 *
 * @author makejava
 * @since 2023-12-04 15:34:31
 */
@Service("userOrganizationService")
public class UserOrganizationServiceImpl implements UserOrganizationService {
    @Resource
    private UserOrganizationMapper userOrganizationMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public UserOrganization queryById(Integer id) {
        return this.userOrganizationMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增数据
     *
     * @param userOrganization 实例对象
     * @return 实例对象
     */
    @Override
    public UserOrganization insert(UserOrganization userOrganization) {
        this.userOrganizationMapper.insert(userOrganization);
        return userOrganization;
    }

    /**
     * 修改数据
     *
     * @param userOrganization 实例对象
     * @return 实例对象
     */
    @Override
    public UserOrganization update(UserOrganization userOrganization) {
        this.userOrganizationMapper.update(userOrganization);
        return this.queryById(userOrganization.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userOrganizationMapper.deleteByPrimaryKey(id) > 0;
    }

    /**
     * 获取用户组织结构列表
     *
     * @param userOrganizationDTO
     * @return
     */
    @Override
    public PageInfo<UserOrganizationVO> findByPage(UserOrganizationDTO userOrganizationDTO) {
        PageHelper.startPage(userOrganizationDTO.getPageNum(), userOrganizationDTO.getPageSize());
        List<UserOrganizationVO> list = userOrganizationMapper.findByPage(userOrganizationDTO);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 添加用户组织机构
     *
     * @param info 添加用户组织机构信息
     */
    @Transactional
    @Override
    public void saveUserOrganization(UserOrganizationListDTO info) {
        // 根据输入的工号查询用户
        UserInfo user = userInfoMapper.selectByNum(info.getNum());
        //List<Integer> roleIdList = userRoleMapper.findUserRole(info.getNum());
        List<UserOrganization> list = new ArrayList<>();
        //获取大区id列表
        List<Integer> centerIdList = info.getCenterIdList();
        //获取部门id列表
        List<Integer> deptIdList = info.getDeptIdList();
        if (/*roleIdList.contains(3)&& */!CollectionUtils.isEmpty(centerIdList)) {
            UserOrganization userOrganization = userOrganizationMapper.selectByNumAndOrganId(info.getNum(), user.getCenterId());
            if (userOrganization == null) {
                //添加用户主显大区
                UserOrganization userCenter = new UserOrganization();
                userCenter.setNum(info.getNum());
                userCenter.setOrganId(user.getCenterId());
                userCenter.setLv(true);
                userCenter.setCreatTime(new Date());
                userCenter.setUpdateTime(new Date());
                userOrganizationMapper.insertSelective(userCenter);
            }else {
                //去除重复组织机构
                List<Integer> organIdList = userOrganizationMapper.selectOrganIdByNum(info.getNum());
                Stream<Integer> streamOther = organIdList.stream();
                Stream<Integer> streamInfo = centerIdList.stream();
                centerIdList = Stream.concat(streamOther, streamInfo).distinct().collect(Collectors.toList());
                centerIdList.removeAll(organIdList);
            }
            //添加用户其他组织机构
            if (centerIdList.contains(user.getCenterId())) {
                centerIdList.remove(user.getCenterId());
            }

            forList(info, list, centerIdList);
            if (!CollectionUtils.isEmpty(deptIdList)) {
                forList(info, list, deptIdList);
            }
            userOrganizationMapper.insertBatch(list);
        } else if (!CollectionUtils.isEmpty(deptIdList)) {
            UserOrganization userOrganization = userOrganizationMapper.selectByNumAndOrganId(info.getNum(), user.getDeptId());
            if (userOrganization == null) {
                //添加用户主显部门
                UserOrganization userDept = new UserOrganization();
                userDept.setNum(info.getNum());
                userDept.setOrganId(user.getDeptId());
                userDept.setLv(true);
                userDept.setCreatTime(new Date());
                userDept.setUpdateTime(new Date());
                userOrganizationMapper.insertSelective(userDept);
            }else {
                //去除重复组织机构
                List<Integer> organIdList = userOrganizationMapper.selectOrganIdByNum(info.getNum());
                organIdList.remove(user.getDeptId());
                Stream<Integer> streamOther = organIdList.stream();
                Stream<Integer> streamInfo = centerIdList.stream();
                deptIdList = Stream.concat(streamOther, streamInfo).distinct().collect(Collectors.toList());
                deptIdList.removeAll(organIdList);
            }
            if (deptIdList.contains(user.getDeptId())) {
                deptIdList.remove(user.getDeptId());
            }
            forList(info, list, deptIdList);
            userOrganizationMapper.insertBatch(list);
        }
    }

    /**
     * 遍历集合添加用户组织结构通用方法
     *
     * @param info         添加用户组织机构信息
     * @param list         用户组织结构集合
     * @param centerIdList 大区id集合
     */
    private void forList(UserOrganizationListDTO info, List<UserOrganization> list, List<Integer> centerIdList) {
        for (int i = 0; i < centerIdList.size(); i++) {
            UserOrganization userOrganization = new UserOrganization();
            userOrganization.setNum(info.getNum());
            userOrganization.setOrganId(centerIdList.get(i));
            userOrganization.setLv(false);
            list.add(userOrganization);
        }
    }

    /**
     * 修改用户组织结构
     * @param info 修改信息
     */
    @Transactional
    @Override
    public void updateUserOrganization(UserOrganizationListDTO info) {
        List<UserOrganization> list = new ArrayList<>();
        //获取大区id列表
        List<Integer> centerIdList = info.getCenterIdList();
        //获取部门id列表
        List<Integer> deptIdList = info.getDeptIdList();
        if (!CollectionUtils.isEmpty(centerIdList)) {
            updateCommon(info, centerIdList);
        } else if (!CollectionUtils.isEmpty(deptIdList)) {
            updateCommon(info, deptIdList);
        }
    }

    /**
     * 修改用户组织结构通用方法
     * @param info 修改信息
     * @param centerIdList 组织结构id集合
     */
    private void updateCommon(UserOrganizationListDTO info, List<Integer> centerIdList) {
        //获取用户组织结构
        List<Integer> organIdList = userOrganizationMapper.selectOrganIdByNum(info.getNum());
        Stream<Integer> streamOther = organIdList.stream();
        Stream<Integer> streamInfo = centerIdList.stream();
        List<Integer> collect = Stream.concat(streamOther, streamInfo).distinct().collect(Collectors.toList());
        List<Integer> collectOrganId = new ArrayList<>(collect);
        collectOrganId.removeAll(centerIdList);
        //删除用户不代管的组织结构
        collectOrganId.forEach(organId -> userOrganizationMapper.deleteOrganization(info.getNum(), organId));
        List<Integer> collectCenter = new ArrayList<>(collect);
        collectCenter.removeAll(organIdList);
        //添加用户新代管的组织结构
        collectCenter.forEach(organId -> userOrganizationMapper.insertAll(info.getNum(), organId));
    }

    @Override
    public void deleteUserOrganization(DeleteUserOrganizationDTO info) {
        userOrganizationMapper.deleteByNumAndOrganId(info.getNum(), info.getOrganId());
    }
}

